from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse

from .models import BlogModel


# Create your views here.
def index(request):
    return render(request, "index.html")


def add(request):
    if request.method == 'GET':
        return render(request, "add.html")
    elif request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        BlogModel.objects.get_or_create(title=title, content=content)
        b_list = BlogModel.objects.all()
        return render(request, 'list.html', context={'b_list': b_list})


def demo_list(request):
    b_list = BlogModel.objects.all()
    return render(request, 'list.html', context={'b_list': b_list})


def detail(request, blog_id):
    blog = BlogModel.objects.get(id=blog_id)
    return render(request, 'detail.html', context={'blog': blog})


def delete(request, blog_id):
    blog = BlogModel.objects.get(id=blog_id)
    if blog:
        blog.delete()
        return redirect(reverse('list'))
    else:
        return HttpResponse("该文章不存在，无法删除！")


def update(request, blog_id):
    blog = BlogModel.objects.get(id=blog_id)
    if request.method == "GET":
        return render(request, "update.html", context={"blog": blog})
    elif request.method == "POST":
        title = request.POST.get('title')
        content = request.POST.get('content')
        blog.title = title
        blog.title = content
        blog.save()
        return redirect(reverse('list'))
    else:
        return HttpResponse("该文章不存在，无法修改")
